package utils.img;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;


public class TesseractImage {
	
	private final String LANG_OPTION = "-l";
//	private final String EOL = System.getProperty("line.separator");
	private String tessPath = new File("tesseract").getAbsolutePath();  //tesseract目录的绝对位置

	public String recognizeText(File imageFile) throws Exception {
		File tempImage = imageFile;  //图片位置

		File outputFile = new File(imageFile.getParentFile(), "output");  //输出文件位置
		
		StringBuffer strB = new StringBuffer();  //保存结果的字符串

		List<String> cmd = new ArrayList<String>();  //存放命令行参数的数组
		
		cmd.add(tessPath + "\\tesseract");

		cmd.add("");
		cmd.add(outputFile.getName());  //输出文件位置
		cmd.add(LANG_OPTION);  //字符类别
		cmd.add("eng");  //英文，找到tessdata里对应的字典文件。

		ProcessBuilder pb = new ProcessBuilder();
		pb.directory(imageFile.getParentFile());

		cmd.set(1, tempImage.getName());  //把图片文件位置放在第一个位置
		
		pb.command(cmd);  //执行命令行
		pb.redirectErrorStream(true);  //通知进程生成器是否合并标准错误和标准输出,把进程错误保存起来。
		Process process = pb.start();  //开始执行进程

		int w = process.waitFor(); //当前进程停止,直到process停止执行，返回执行结果.
//		System.out.println("Exit value = "+w);

		// delete temp working files
//		tempImage.delete();

		if (w == 0) {
			BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(outputFile
					.getAbsolutePath()
					+ ".txt"), "UTF-8"));

			String str;

			while ((str = in.readLine()) != null) {
				strB.append(str);
			}
			in.close();
		} else {
			String msg;
			switch (w) {
			case 1:
				msg = "Errors accessing files. There may be spaces in your image's filename.";
				break;
			case 29:
				msg = "Cannot recognize the image or its selected region.";
				break;
			case 31:
				msg = "Unsupported image format.";
				break;
			default:
				msg = "Errors occurred.";
			}
			
			throw new RuntimeException(msg);
		}

		new File(outputFile.getAbsolutePath() + ".txt").delete();
		
		return strB.toString();
	}
	
	public static void main(String[] args) throws Exception{
		System.out.println(new TesseractImage().recognizeText(new File("6474.bmp")));
	}

}
